package com.keeping.aiimagery.service.impl;

import com.alipay.api.AlipayApiException;
import com.keeping.aiimagery.entity.Alipay.AliPayBean;
import com.keeping.aiimagery.entity.Alipay.OrderDTO;
import com.keeping.aiimagery.entity.Alipay.ResponseDTO;
import com.keeping.aiimagery.entity.Untils.AlipayUntil;
import com.keeping.aiimagery.service.IStoreService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@Transactional
public class StoreServiceImpl implements IStoreService {
    @Resource
    private AlipayUntil aliPayUtil;

    @Override
    public ResponseDTO<String> aliPayOrder(OrderDTO orderDTO){
        String totalPrice = orderDTO.getPrice();
        UUID uuid = UUID.randomUUID();
        String orderNo =  uuid.toString().replace("-", "").substring(0, 32);
        return initAliPay(orderNo, totalPrice,orderDTO.getName(),orderDTO.getBody(),orderDTO.getUserId().toString(),orderDTO.getId());
    }

    /**
     * 初始化支付信息
     * @param orderNo
     * @param totalPrice
     * @return
     */
    public ResponseDTO<String> initAliPay(String orderNo, String totalPrice,String subject,String integral,String userId,Integer id) {
        // 封装沙箱支付宝支付信息
        AliPayBean alipayBean=new AliPayBean();
        alipayBean.setOut_trade_no(orderNo);
        alipayBean.setSubject(subject);
        alipayBean.setTotal_amount(totalPrice);
        Map<String,String> map=new HashMap<>();
        map.put("Id",id.toString());
        map.put("userId",userId);
        map.put("integral",integral);
        alipayBean.setBody(map.toString());
        String pay = null;
        try {
            pay = aliPayUtil.pay(alipayBean);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return ResponseDTO.success(pay);
    }

    /**
     * 沙箱支付宝成功支付回调接口
     * @param orderDTO
     * @return
     */
    @Override
    public ResponseDTO<Boolean> aliPayOrderSuccess(OrderDTO orderDTO) 	{
        // 这里可以写一些回调的接口逻辑，比如更新订单状态
        // 因为我们这有一个OrderDTO的入参，我们可以使用这个实体里面的订单号字段来获取详细订单信息
        return ResponseDTO.successByMsg(true, "支付成功！");
    }
}
